package persistencia;

import entidades.Cliente;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import negocio.Central;
import negocio.Util;

public class ClienteDAO {
    
    String csv = "bd/cliente.csv";
    
    public ArrayList<Cliente> carrega() throws FileNotFoundException, IOException{
        ArrayList<Cliente> clienteArray = new ArrayList<Cliente>();
        BufferedReader br = new BufferedReader(new FileReader(csv));
        String l = br.readLine();
        while(l!=null){
            String[] lsplit = l.split(";");
            Cliente c = new Cliente();
            c.setIdCliente(Integer.parseInt(lsplit[0].trim()));
            c.setNome(lsplit[1].trim());
            c.setCpf(lsplit[2].trim());
            c.setRg(lsplit[3].trim());
            c.setEndereco(lsplit[4].trim());
            c.setTelefone(Integer.parseInt(lsplit[5].trim()));
            clienteArray.add(c);
            l=br.readLine();
        }
        br.close();
        return clienteArray;
    }
    
    public void insere(Cliente c) throws IOException{
        BufferedWriter bw = new BufferedWriter(new FileWriter(csv,true));
        bw.write(c.getIdCliente()+";"+c.getNome()+";"+c.getCpf()+";"+c.getRg()+";"+c.getEndereco()+
                ";"+c.getTelefone()+"\n");
        bw.close();
    }
    
    public void remove(ArrayList<Cliente> clienteArray, Cliente cRemove) throws IOException{
        Util.criaArquivo(csv);
        for(Cliente c : clienteArray){
            if (!c.equals(cRemove)) insere(c);
        }
    }
    
    public void modifica(ArrayList<Cliente> clienteArray) throws IOException{
        Util.criaArquivo(csv);
        for(Cliente c : clienteArray){
            insere(c);
        }
    }
}
